package initialization

import (
	"gitee.com/danlansky/go-library/base/db"
	"gitee.com/danlansky/go-library/logs"
	"gitee.com/danlansky/go-library/repository/mysqldb"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"sync"
)

var dbOnce sync.Once

const (
	defaultDatabaseConfigTag = "mysql"
	databaseDefaultNameTag   = "database.default.name"
)

func initDatabase() {
	dbOnce.Do(func() {
		rwConfigMap := make(map[string]mysqldb.MysqlSetting)
		_ = viper.UnmarshalKey(defaultDatabaseConfigTag, &rwConfigMap)

		// 加载数据库配置 初始化
		for _, databaseConfig := range rwConfigMap {
			conn := mysqldb.InitMysqlDB(databaseConfig)
			conn.SetLogger(logs.MysqlLogger{})
			db.MysqlConnectMap[databaseConfig.Name] = conn
			logs.AccessLog("Database init", zap.String("database", databaseConfig.Name))

		}
		// 如果没有配置数据库 则不用检查默认值
		if len(rwConfigMap) != 0 {
			var errMsg interface{}
			if viper.GetString(databaseDefaultNameTag) == "" {
				errMsg = databaseDefaultNameTag + " is null"
				panic(errMsg)
			}
			logs.AccessLog("Default database connection", zap.String("default", viper.GetString("database.default.name")))
		}
	})
}
